<template>
  <div class="room-container">
    <!-- 房间列表 -->
    <div class="room-list">
      <div v-for="room in rooms" :key="room.roomId" class="room-item">
        <span>房间号: {{ room.roomId }}</span>
        <span>人数: {{ room.currentPlayers }}/{{ room.maxPlayers }}</span>
        <button @click="joinRoom(room.roomId)">加入</button>
      </div>
    </div>

    <!-- 创建房间表单 -->
    <div class="create-room-form">
      <h3>创建房间</h3>
      <input v-model="newRoomPassword" type="password" placeholder="房间密码（可选）" />
      <input v-model="newRoomMaxPlayers" type="number" placeholder="最大玩家数（2-4）" min="2" max="4" />
      <button @click="createRoom">创建房间</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { loadRooms, joinRoom as joinRoomService, createRoom as createRoomService } from '@/services/api';

const rooms = ref([]);
const newRoomPassword = ref(''); // 新房间的密码
const newRoomMaxPlayers = ref(2); // 新房间的最大玩家数，默认为2

// 加载房间列表
const loadRoomsList = async () => {
  try {
    const response = await loadRooms();
    console.log(response.data);
    rooms.value = response.data.data; 
    console.log(rooms.value);
  } catch (err) {
    alert('加载房间列表失败: ' + (err.response?.data?.message || '未知错误'));
  }
};

// 加入房间
const joinRoom = async (roomId) => {
  try {
    const password = prompt('输入房间密码（可选）', '');
    const response = await joinRoomService({ roomId, password }); // 调用 joinRoomService
    alert('加入房间成功: ' + response.data.message); // 显示后端返回的成功信息
    // 可以在这里跳转到对战页面
  } catch (err) {
    alert('加入房间失败: ' + (err.response?.data?.message || '未知错误'));
  }
};

// 创建房间
const createRoom = async () => {
  try {
    const maxPlayers = parseInt(newRoomMaxPlayers.value, 10);
    if (isNaN(maxPlayers) || maxPlayers < 2 || maxPlayers > 4) {
      alert('最大玩家数必须在2到4之间');
      return;
    }

    const response = await createRoomService({
      password: newRoomPassword.value,
      maxPlayers
    });
    alert('创建房间成功: ' + response.data.message); // 显示后端返回的成功信息
    // 可以在这里跳转到房间列表或其他页面
    await loadRoomsList(); // 刷新房间列表
  } catch (err) {
    alert('创建房间失败: ' + (err.response?.data?.message || '未知错误'));
  }
};

onMounted(loadRoomsList);
</script>

<style scoped>
.room-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.room-list {
  margin-bottom: 20px;
}

.room-item {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 5px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.create-room-form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.create-room-form input {
  margin: 5px 0;
  padding: 5px;
}

.create-room-form button {
  padding: 5px 10px;
  margin-top: 10px;
}
</style>